import { queryAllClassification } from '@/apis/Classification'
import type { Classification } from '@/models/Classification/Classification'
import { notification } from 'ant-design-vue'
import { ref, type Ref } from 'vue'

export function useClassification() {
  const classificationList = ref<Classification[]>([])
  const secondaryClassificatListMapCache: Ref<Record<string, Classification[]>> = ref({})

  function addSecondaryClassificatListMapCache(parentCode: string, data: Classification[]) {
    secondaryClassificatListMapCache.value = {
      ...secondaryClassificatListMapCache.value,
      [parentCode]: data,
    }
  }

  const loadingClassificationList = ref(false)

  async function initClassificationList() {
    if (loadingClassificationList.value) return
    loadingClassificationList.value = true
    try {
      const res = await queryAllClassification()
      if (Array.isArray(res.data)) {
        classificationList.value = res.data
      } else {
        classificationList.value = []
        notification.error({ message: `获取一级分类失败失败!` })
      }
    } catch (error) {
      classificationList.value = []
      notification.error({ message: `获取一级分类失败失败!` })
    }
    loadingClassificationList.value = false
  }

  initClassificationList()

  return {
    classificationList,
    loadingClassificationList,
    secondaryClassificatListMapCache,
    addSecondaryClassificatListMapCache,
  }
}
